#include <iostream>
#include <vector>

using namespace std;
class Solution
{
public:
   bool buddyStrings(string s, string goal)
   {
      if (s.size() != goal.size())
      {
         return false;
      }

      if (s == goal)
      {
         vector<int> count(26);
         for (int i = 0; i < s.size(); i++)
         {
            count[s[i] - 'a']++;
            if (count[s[i] - 'a'] > 1)
            {
               return true;
            }
         }
         return false;
      }
      else
      {
         int first = -1, second = -1;
         for (int i = 0; i < s.size(); i++)
         {
            if (s[i] != goal[i])
            {
               if (first == -1)
                  first = i;
               else if (second == -1)
                  second = i;
               else
                  return false;
            }
         }

         return (second != -1 && s[first] == goal[second] && s[second] == goal[first]);
      }
   }

   bool buddyStrings_2(string s, string goal)
   {
      // 字符串长度不相等, 直接返回false
      if (s.size() != goal.size())
         return false;
      int a = -1, b = -1, n = s.size(), c[26] = {0}, ds = 0;
      for (int i = 0; i < n; ++i)
      {
         // 字符串相等的时候, 只要有重复的元素就返回true
         if (++c[s[i] - 'a'] == 2)
            ds = true;
         // A, B字符串有不相等的两个地方, 需要查看它们交换后是否相等即可.
         if (s[i] != goal[i])
         {
            if (b == -1)
               a = s[i], b = goal[i];
            else if (a != goal[i] || b != s[i])
               return false;
            else
               a = -1;
         }
      }
      return a == -1 && (b != -1 || ds);
   }
};
int main()
{

   system("pause");
   return 0;
}
